package com.skh.search;

/*
二分查找
 */
public class BinarySearch {

    /*
    循环实现
     */
    public int bserach(int[] nums, int target) {
        int low = 0;
        int high = nums.length - 1;
        while (low <= high) {
            //获取中间坐标
            int mid = low + (high - low) / 2;
            if (nums[mid] < target) {
                //如果小于查找值,则从数组的右边继续查找
                low = mid + 1;
            } else if (nums[mid] > target) {
                //如果中间值大于查找值，则从数组的左边继续查找
                high = mid - 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    /*
    递归实现
     */
    public int rsearch(int[] nums, int target, int low, int high) {
        if (low > high) {
            return -1;
        }
        //计算中间坐标
        int mid = low + (high - low) / 2;
        if (nums[mid] > target) {
            //如果中间值大于查找值，则从数组的左边继续查找
            return rsearch(nums, target, low, mid - 1);
        } else if (nums[mid] < target) {
            //如果中间值小于查找值，则从数组的右边继续查找
            return rsearch(nums, target, mid + 1, high);
        } else {
            return mid;
        }
    }

    public static void main(String[] args) {

        int[] nums = {1, 2, 3, 4, 5, 7, 8};
        int target = 7;
        BinarySearch binarySearch = new BinarySearch();
        int result = binarySearch.bserach(nums, target);
        System.out.println("result = " + result);

        int result1 = binarySearch.rsearch(nums, target, 0, nums.length - 1);
        System.out.println("result1 = " + result1);
    }
}
